package com.linux.huhx.incepters;

import com.alibaba.fastjson.JSONObject;
import com.linux.huhx.constants.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Map;

/**
 * Created by huhx on 2017-05-15.
 */
public class JsonParseInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = LoggerFactory.getLogger(JsonParseInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String methodType = request.getMethod();
        String contentType = request.getContentType();
        logger.info("request method is " + methodType + ", and contenttype is " + contentType);
        // 如果是post的文件请求，那么return
        if (methodType.toUpperCase().equals("POST") && contentType.contains("multipart/form-datas")) {
            return true;
        }

        // 得到请求的内容
        String requestContent = null;
        if (methodType.toUpperCase().equals("GET")) {
            requestContent = request.getQueryString();
            requestContent = URLDecoder.decode(requestContent, "utf-8");
            String[] arr = requestContent.split("&");
            for (int i = 0; i < arr.length; i++) {
                String[] str = arr[i].split("=");
                if (str.length == 1) {
                    request.setAttribute(str[0], "");
                } else {
                    request.setAttribute(str[0], str[1]);
                }
            }
        } else if (methodType.toUpperCase().equals("POST")) {
            requestContent = getPostContent(request);
            requestContent = URLDecoder.decode(requestContent, "utf-8");
            @SuppressWarnings("unchecked")
            Map<String, Object> map = JSONObject.parseObject(requestContent, Map.class);
            request.setAttribute(Constants.REQUEST_DATA_MAP, map);
        }
        logger.info("request content is " + requestContent);
        return true;
    }

    // 得到post方式请求的数据
    private String getPostContent(HttpServletRequest request) {
        int contentLength = request.getContentLength();
        byte[] content = new byte[contentLength];
        InputStream stream = null;
        int offset = 0;
        while (offset < contentLength) {
            try {
                stream = request.getInputStream();
                int realLength = stream.read(content, offset, contentLength - offset);
                if (realLength == -1) {
                    return null;
                }
                offset += realLength;
            } catch (IOException e) {
                logger.error("Read post content appear error: " + e);
            } finally {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    stream = null;
                }
            }
        }
        return new String(content);
    }
}
